package masterSpringMvc.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import masterSpringMvc.service.TweetService;

@Controller
public class TweetController {
	@Autowired
	private TweetService tweetService;
	
	@RequestMapping("/")
	public String index(Model model)
	{
		String result = this.tweetService.getList().get(0);
		model.addAttribute("message",result);
		return "resultPage";
	}
	
	@RequestMapping("search")
	public String search()
	{
		return "search";
	}
	
	@RequestMapping("results")
	public String results(String search,Model model)
	{
		model.addAttribute("search",search);
		model.addAttribute("tweets",tweetService.getList());
		return "resultsPage";
	}
	
	@RequestMapping(value = "/postSearch",method=RequestMethod.POST)
	public String postSearch(HttpServletRequest request,RedirectAttributes redirectAttributes) 
	{
		String search = request.getParameter("search");
		if(search.toLowerCase().contains("structs")) {
			redirectAttributes.addFlashAttribute("error", "Try using spring instead");
			return "redirect:/search";
		}
		redirectAttributes.addAttribute("search",search);
		return "redirect:/results";
	}
}
